<?php
declare (strict_types=1);

namespace app\service;

use think\App;
use Symfony\Component\DomCrawler\Crawler;

class HtmlParseService extends \think\Service
{
    public function __construct(App $app)
    {
        parent::__construct($app);

    }

    static function handle()
    {
        $files = glob(app_path('data') . 'market_content\html\*.html');
        $savePath = app_path('data') . 'market_content\json/';
        foreach ($files as $file) {
            $data = self::parse($file);
            if (isset($data['file']) && 5 == $data['c']) {

                file_put_contents($savePath . $data['file'] . '.json', json_encode($data,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
            }
        }
    }

    static function parse($file)
    {
        $c = file_get_contents($file);
        $data = [];
        $crawler = new Crawler($c);

        $crawler->filter('div.font28.b.ttl')->each(function ($node) use (&$data) {
            // 获取标签内的文本
            $data['title'] = trim($node->text());
        });
        $crawler->filter('div.desc.c666.line18em')->each(function ($node) use (&$data) {
            // 获取标签的 HTML 内容
            $data['snopi'] = trim($node->text());
        });
        $crawler->filter('ul.lijian li > div')->each(function ($node) use (&$data) {
            // 获取标签内的文本
            $text = strip_tags($node->html());
            $items = explode('：', $text);
            $items = array_map('trim', $items);
            $data['items'][$items[0]] = $items[1];
        });
        $crawler->filter('div.cont.c666.line18em')->each(function ($node) use (&$data) {
            // 获取标签的 HTML 内容
            $data['desc'] = trim($node->html());
        });
        $data ['file'] = basename($file);
        $data['c'] = count($data);
        return $data;
    }


}
